package com.huaxin.device.mapping;

import com.huaxin.device.dto.request.CollectedDataRecordCreateReqDTO;
import com.huaxin.device.dto.request.CollectedDataRecordUpdateReqDTO;
import com.huaxin.device.models.CollectedDataRecord;
import com.huaxin.hxenum.enums.DataQuality;
import com.huaxin.hxenum.enums.DataType;
import com.huaxin.hxenum.enums.Unit;
import org.mapstruct.AfterMapping;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.MappingTarget;

@Mapper(componentModel = "spring")
public interface CollectedDataRecordMapping {

    @Mapping(target = "unit", ignore = true)
    @Mapping(target = "valueType", ignore = true)
    @Mapping(target = "quality", ignore = true)
    CollectedDataRecord toEntity(CollectedDataRecordCreateReqDTO in);

    @AfterMapping
    default void afterCreateMapping(CollectedDataRecordCreateReqDTO in, @MappingTarget CollectedDataRecord entity) {
        entity.setUnit(Unit.of(in.getUnit()));
        entity.setValueType(DataType.of(in.getValueType()));
        if (in.getQuality() != null) {
            entity.setQuality(DataQuality.valueOf(in.getQuality().trim().toLowerCase()));
        }
    }

    @Mapping(target = "unit", ignore = true)
    @Mapping(target = "valueType", ignore = true)
    @Mapping(target = "quality", ignore = true)
    void updateEntity(CollectedDataRecordUpdateReqDTO in, @MappingTarget CollectedDataRecord entity);

    @AfterMapping
    default void afterUpdateMapping(CollectedDataRecordUpdateReqDTO in, @MappingTarget CollectedDataRecord entity) {
        if (in.getUnit() != null) {
            entity.setUnit(Unit.of(in.getUnit()));
        }
        if (in.getValueType() != null) {
            entity.setValueType(DataType.of(in.getValueType()));
        }
        if (in.getQuality() != null) {
            entity.setQuality(DataQuality.valueOf(in.getQuality().trim().toLowerCase()));
        }
    }
}